import { defineStore } from "pinia";
import { ref, computed, reactive } from "vue";
import { useDark, useToggle, useFullscreen } from "@vueuse/core";
import router from "@/router/index";

export const useLayoutStore = defineStore("layout", () => {
	// 侧边栏伸缩相关
	const isCollapse = ref(false);
	const asideWidth = computed(() => (isCollapse.value ? "64px" : "200px"));

	// 暗黑模式相关
	const isDark = useDark();
	const toggleDark = () => {
		isDark.value = !isDark.value;
		useToggle(isDark);
	};

	// 全屏相关
	const { toggle } = useFullscreen();
	const toggleFullscreen = () => {
		toggle();
	};

	// tags标签页
	const headerTags = ref([]); // tags渲染该数组
	const mapHasTag = new Set(); // 当前已添加的tag, 只用于使用has方法判断当前路由是否已经添加过, 元素值是: path
	const allRoutes = reactive({ isInit: false, routes: {} });
	// 点击左侧菜单时, 会触发该方法
	const addTags = (routeInfo) => {
		// 判断该path是否已经存在, 存在则停止.
		if (mapHasTag.has(routeInfo.index)) return;

		// 如果没有初始化, 则将所有路由添加到allRoutes中, 格式为 { path: 路由对象 }
		if (!allRoutes.isInit) {
			router.getRoutes().forEach((item) => (allRoutes.routes[item.path] = item));
			allRoutes.isInit = true;
		}

		mapHasTag.add(routeInfo.index);
		headerTags.value.push(allRoutes.routes[routeInfo.index]);
	};
	const removeTags = (tagInfo, tagIndex) => {
		// 如果点击的是当前路由, 则跳转到左侧路由
		if (tagInfo.path === router.currentRoute.value.path) router.push(headerTags.value[tagIndex - 1].path);
		// 删除tag
		mapHasTag.delete(tagInfo.path);
		headerTags.value.splice(tagIndex, 1);
	};
	const clickTags = (tagInfo) => {
		router.push(tagInfo.path);
	};
	// 清空tags
	const clearTags = () => {
		headerTags.value = [];
		mapHasTag.clear();
	};

	// 需要缓存的组件
	const keepAliveComponents = computed(() => {
		const keepAliveRes = [];
		headerTags.value.forEach((tagRouteItem) => {
			if (tagRouteItem.meta.keepAlive) keepAliveRes.push(tagRouteItem.name);
		});

		return keepAliveRes;
	});

	return {
		isCollapse,
		asideWidth,

		isDark,
		toggleDark,

		toggleFullscreen,

		headerTags,
		addTags,
		removeTags,
		clickTags,
		clearTags,

		keepAliveComponents,
	};
});
